#!/bin/sh

BACKUP_VAR=overlay_backup
RESTORE_DIR=/overlay

overlay_check() {
	grep -q upperdir=/overlay /proc/mounts || { echo "Overlay not mounted, exit"; exit; }
}

backup() {
	overlay_check
	# Calculate the free space in the U-Boot environment, rough estimate.
	env_size=$(fw_printenv | wc -c)
	total_size=$((64 * 1024))
	buffer=2048
	free_space=$((total_size - env_size))
	available_space=$((free_space - buffer))

	# Create the archive base64 data and calculate its size
	encoded_data=$(tar -cf - -C /overlay . | gzip -9 | base64)
	size=$(echo "$encoded_data" | wc -c)

	# Check if the archive base64 fits within the available space with the buffer
	if [ "$size" -le "$available_space" ]; then
		echo "Data: $size bytes, ENV Used: $env_size bytes, ENV Free: $available_space bytes... Size OK, proceed."
		# Backup the overlay data directly into the U-Boot environment variable
		fw_setenv $BACKUP_VAR "$encoded_data"
		echo "Backup saved to U-Boot environment variable '$BACKUP_VAR'."
	else
		echo "Backup archive base64 size exceeds the available space. Free space: $available_space bytes, File size: $size bytes."
	fi
}

restore() {
	overlay_check
	# Get the base64-encoded tar.gz data from the environment variable '$BACKUP_VAR'
	encoded_data=$(fw_printenv -n $BACKUP_VAR)

	# Decode the base64 data, decompress, and extract it
	if [ -n "$encoded_data" ]; then
		echo "$encoded_data" | base64 -d | gzip -d | tar -xf - -C $RESTORE_DIR
		echo "Data extracted to $RESTORE_DIR"
	else
		echo "No data found in the '$BACKUP_VAR' environment variable."
	fi
}

clear_env() {
	fw_setenv $BACKUP_VAR
	echo "Environment variable '$BACKUP_VAR' cleared."
}

# Main
case "$1" in
	-b|--backup)
		backup
		;;
	-r|--restore)
		restore
		;;
	-c|--clear)
		clear_env
		;;
	*)
		echo "EXPERIMENTAL: Backup /overlay to ENV"
		echo "Usage: $0 [-b|--backup] [-r|--restore] [-c|--clear]"
		exit 1
		;;
esac
